package com.wider.servlets;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;

import com.wider.servlet.MultipartFormData;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.mail.MessagingException;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class echo
 */
public class FileTestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Logger  logger;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FileTestServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @throws IOException 
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    protected void Get_action(HttpServletRequest request, HttpServletResponse response) throws IOException
    {
    	PrintWriter rspndr = response.getWriter();
		rspndr.println("Echo )))");
		Iterator paramkit = request.getParameterMap().keySet().iterator();
		String paramkey;

		while (paramkit.hasNext()){
                    paramkey = paramkit.next().toString();
                    rspndr.println(paramkey + "=" + request.getParameter(paramkey).toString());
		}
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		Get_action(request, response);
	}

	/**
	 * @throws IOException 
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void read_path_ask(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		PrintWriter rspndr = response.getWriter();
		 MultipartFormData formdata = new MultipartFormData(request);
         Iterator paramit = formdata.getParameterMap().entrySet().iterator();
         while(paramit.hasNext()){
         	
             Map.Entry<Object, Object> param = (Map.Entry<Object, Object>) paramit.next();
             Object paramkey = param.getKey();
             Object paramval = param.getValue();
             rspndr.println("in "+"Parameter: " + paramkey + " : " + paramval);
         }
		
	}
	
	protected void Post_action(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		 PrintWriter rspndr = response.getWriter();
		 rspndr.println(request.getContentType().toLowerCase().toString());
		 
         rspndr.println("received:");
         MultipartFormData formdata = new MultipartFormData(request);
         Iterator paramit = formdata.getParameterMap().entrySet().iterator();
        
         rspndr.println("hi "+paramit.hasNext());
         while(paramit.hasNext()){
        	
             Map.Entry<String, Object> param = (Map.Entry<String, Object>) paramit.next();
             String paramkey = param.getKey();
             Object paramval = param.getValue();
             rspndr.println("in "+"Parameter: " + paramkey + " : " + paramval);
           //  System.out.println("Parameter: " + paramkey + " : " + paramval);

           if (paramval.getClass().getName() == ArrayList.class.getName()){
                 System.out.println("Found ArrayList.");
                 ArrayList<String> files = (ArrayList<String>) paramval;
                 try {
                     int ret = 0;

                     ret = formdata.saveFiles(files, "/home/sky/wel");
                     System.out.println("Files saved? " + ret);
                 } catch (Exception e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
                 }
             }
         }		
	}
	 
	
	public void make_response(Map<Object, Object> params, HttpServletResponse response) throws  IOException, MessagingException {
	        try {
	            //Retrieve the parameters and construct the params string
	            Iterator paramsit = params.entrySet().iterator();

	            //Instanciate an MimeMultipart as a container
	            MimeMultipart multipart = new MimeMultipart();
	            multipart.setSubType("form-data");

	            //Iterates each parameter pair
	            while (paramsit.hasNext()) {
	                //Get the key-value pair from the Iterator
	                Map.Entry param = (Map.Entry) paramsit.next();
	                Object paramkey = param.getKey();
	                Object paramval = param.getValue();

	                //Construct the bodypart according to the type, then attach it to the Multipart
	                //If the paramkey is type of File, the paramval will be used as the key of the bodypart
	                if (paramkey.getClass().equals(File.class)){
	                    File file = (File) paramkey;
	                    MimeBodyPart mimebody = new MimeBodyPart();
	                    mimebody.setDisposition("file; name=" + (String)paramval);
	                    mimebody.attachFile(file);
	                    multipart.addBodyPart(mimebody);
	                } else {
	                    //Not a file, currently supports SetText only
	                    String content = paramval.toString();
	                    MimeBodyPart mimebody = new MimeBodyPart();
	                    mimebody.setDisposition("form-data; name=" + paramkey);
	                    mimebody.setText(content);
	                    multipart.addBodyPart(mimebody);
	                }
	            }

	          

	            //Attach the multipart to the connection stream
	          
	            multipart.writeTo(response.getOutputStream());
	            
	          

	        }/*catch (MalformedURLException ex) {
	            logger.log(Level.WARNING, "MalformedURLException occurs at the base URL.", ex);
	            throw ex;
	        }*/catch (IOException ex) {
	            logger.log(Level.WARNING, "IOException occurs while starting the HTTP POST transaction.", ex);
	            throw ex;
	        }catch (MessagingException ex) {
	            logger.log(Level.WARNING, "MessagingException occurs while starting the HTTP POST transaction.", ex);
	            throw ex;
	        }

	    }
	
	 public void make_path_reponse(String root,HttpServletRequest request, HttpServletResponse response) throws IOException, MessagingException
		{
		 HashMap<Object, Object> params = new HashMap<Object, Object>();
		 String path;
		 String separator=File.separator;
		
		 
		 File now=new File(root);
		 for(int loop=0;loop<now.listFiles().length;loop++)
		 {
			 path=root + separator + now.list()[loop].toString();
			 
			  params.put(loop, path);
		 }
		 
		 make_response( params,response);
		
		}
	 
	protected void sendback(HttpServletRequest request, HttpServletResponse response) throws IOException, MessagingException
	{
		 HashMap<Object, Object> params = new HashMap<Object, Object>();
         params.put("ppid", 100);
         params.put("name", "Cola Lou");
         params.put("weight", 23.3317);
         params.put("supersuperpower", "1000%");
         
        
        	 make_response( params,response);
        
		
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	
		//Post_action(request, response);
		
		
			
				//sendback(request, response);
			
		
			
				/*try {
					make_path_reponse("/home",request,response);
				} catch (MessagingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}*/
		read_path_ask( request, response);
			
		
		
	}

}
